%include 'boot.inc'
section MBR vstart=0x7c00

	mov ax,cs
	mov ss,ax
	mov es,ax
	mov ds,ax
	mov fs,ax
	mov gs,ax
	mov sp,0x7c00

	;clear screen
	mov ax,0x600
	mov bx,0x700
	mov cx,0x00
	mov dx,0x184f
	int 0x10
	
	;set cursor to origin
	mov ax,0x2
	mov bh,0
	mov dx,0x00
	int 0x10

	;get cursor pos
	mov ax,0x3
	mov bx,0
	int 0x10

	;print message
	mov ax,0x1301
	mov cx,M_LEN
	mov bp,message
	mov bx,0x2
	int 0x10
	
	;load loader to memory at LOADER_BASE_ADDR
	mov ax,LOADER_LBA
	mov cx,LOADER_SECTOR
	mov bx,LOADER_BASE_ADDR
	call rd_disk_16

	;here we go loader
	jmp LOADER_BASE_ADDR

	;eax LBA ADDR
	;cx  sector count
	;bx  addr where we load
rd_disk_16:
	;set sector count
	mov bp,sp
	push cx
	push ax

	mov dx,ATA0_CBR_M_SCTOR_COUNT
	mov ax,cx
	out dx,al
	
	;set LBA LOW
	mov dx,ATA0_CBR_M_LBA_LOW
	mov ax,[bp-4]
	out dx,al
	;set LBA MID
	mov dx,ATA0_CBR_M_LBA_MID
	mov cx,8
	shr ax,cl
	out dx,al
	;set LBA HI
	mov dx,ATA0_CBR_M_LBA_HI
	mov cx,16
	mov ax,[bp-4]
	shr ax,cl
	out dx,al
	
	;set LBA Last
	mov dx,ATA0_CBR_M_DEV
	mov ax,[bp-4]
	mov cx,24
	shr ax,cl
	and ax,0x0f
	out dx,al
		
	;set device port set master device use LBA MODE
	xor ax,ax
	or  ax,0xE0	
	out dx,al
	
	;tell ATA0 master channle read now
	mov dx,ATA0_CBR_M_COMMAND
	mov al,CBR_COMMAND_READ
	out dx,al
	
.not_ready:
	nop
	nop
	mov dx,ATA0_CBR_M_STATUS
	in al,dx	
	and al,0x08
	cmp al,0x08
	jnz .not_ready
		
	;sector count to ax	
	mov ax,[bp-2]
	mov dx,256
	mul dx
	mov cx,ax
	
	mov dx,ATA0_CBR_M_DATA
.go_on_read:
	in ax,dx
	mov [bx],ax
	add bx,2
	loop .go_on_read

	pop ax
	pop cx
	ret	

	message db "welcome to my world",0x0a,0x0d
	M_LEN equ $-message
	times (510-($-$$)) db 0
	db 0x55,0xaa
